package me.zhengjie.modules.biz.utils;

import gnu.io.*;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/*
 * type 传感器类型
 * 1.各种气体和温度
 * 2.湿度
 *
 * */

/**
 * @name: SerialPortUtilTest
 * @author: tuacy.
 * @date: 2019/6/26.
 * @version: 1.0
 * @Description: 串口测试代码
 */
public class SerialPortUtilTest {
    static CommPortIdentifier portManager;
    // 有效连接上的端口的枚举
    static Enumeration<?> portList;


    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        // 由高位到低位
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }

    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (bytes[i] & 0x000000FF) << shift;// 往高位游
        }
        return value;
    }

    public static byte[] toByteArray(String hexString) {
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {//因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }

    public static String toHexString(byte[] byteArray) {
        if (byteArray == null || byteArray.length < 1)
            throw new IllegalArgumentException("this byteArray must not be null or empty");

        final StringBuilder hexString = new StringBuilder();
        for (byte b : byteArray) {
            if ((b & 0xff) < 0x10)//0~F前面不零
                hexString.append("0");
            hexString.append(Integer.toHexString(0xFF & b));
        }
        return hexString.toString().toLowerCase();
    }

    /**
     * 测试获取串口列表
     */

    public void getSystemPortList() {

        List<String> portList = SerialPortUtil.getSerialPortList();

    }


    /**
     * 测试串口打开，读，写操作
     */
    public void serialPortAction(int type, DataHandlerInterface dataHandlerInterface) {
        try {
            ArrayList<String> data = new ArrayList<>();

            final SerialPort serialPort = SerialPortUtil.openSerialPort("COM3", 9600);
            //启动一个线程每2s向串口发送数据，发送1000次hello
            AtomicReference<String> send = new AtomicReference<>("");
            new Thread(() -> {
                if (type == 1) {
                    send.set("FF039C4200025F91");
                } else {
                    send.set("FF039C4700024F90");
                }
                SerialPortUtil.sendData(serialPort, toByteArray(send.get()));//发送数据

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }).start();
            //设置串口的listener
            SerialPortUtil.setListenerToSerialPort(serialPort, event -> {
                //数据通知
                if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                    byte[] bytes = SerialPortUtil.readData(serialPort);
                    ArrayList<String> sendReceive = new ArrayList<>();
                    for (byte b : bytes) {
                        String x = Integer.toBinaryString((b & 0xFF) + 0x100).substring(1);
                        int i = b & 0xff;
                        sendReceive.add(String.format("%02x", b));
                    }
                    if (Objects.equals(sendReceive.get(1), "03") && Objects.equals(sendReceive.get(2), "04")) {
                        String currentData = sendReceive.get(3) + sendReceive.get(4) + sendReceive.get(5) + sendReceive.get(6);
                        int x = Integer.parseInt(currentData, 16);
                        data.add(sendReceive.get(0));
                        data.add(String.valueOf(x));
                        System.out.println(data);
                        dataHandlerInterface.OnDataReceive(data);
                    }
                    portList = CommPortIdentifier.getPortIdentifiers();
                }
            });
            try {
                // sleep 一段时间保证线程可以执行完
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            serialPort.close();
            System.out.println("关闭串口 " + serialPort.getName());
        } catch (NoSuchPortException | PortInUseException | UnsupportedCommOperationException | TooManyListenersException e) {
            e.printStackTrace();
        }
    }

    public interface DataHandlerInterface {
        void OnDataReceive(ArrayList<String> data);
    }
}



